# -*- coding: utf-8 -*-
import os
import oss2

class OSSUploader:
    def __init__(self):
        # 从环境变量获取 OSS 配置
        self.access_key_id = os.getenv('ALIYUN_AK_ID')
        self.access_key_secret = os.getenv('ALIYUN_AK_SECRET')
        self.endpoint = os.getenv('OSS_ENDPOINT')  # 例如：'http://oss-cn-shanghai.aliyuncs.com'
        self.bucket_name = os.getenv('OSS_BUCKET_NAME')
        
        # 创建 Bucket 实例
        auth = oss2.Auth(self.access_key_id, self.access_key_secret)
        self.bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)

    def upload_file(self, local_file_path, oss_file_path):
        """
        上传文件到 OSS
        :param local_file_path: 本地文件路径
        :param oss_file_path: OSS 上的文件路径
        :return: OSS 文件访问 URL
        """
        try:
            # 上传文件
            self.bucket.put_object_from_file(oss_file_path, local_file_path)
            
            # 生成文件 URL（默认有效期 3600 秒）
            url = self.bucket.sign_url('GET', oss_file_path, 3600)
            return url
            
        except Exception as e:
            print(f"上传文件到 OSS 失败: {str(e)}")
            return None